/*
 * Copyright (C) 2018 The GadTry Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.harbby.gadtry.collection.offheap;

import com.github.harbby.gadtry.base.Platform;
import sun.misc.Unsafe;

public class OffHeapIntArray
{
    private static final Unsafe unsafe = Platform.getUnsafe();

    private final long address;

    public OffHeapIntArray(int len)
    {
        address = Platform.allocateMemory((long) len << 2);
    }

    public long getAddress()
    {
        return address;
    }

    public static int[] getInts(long address, int count)
    {
        int[] values = new int[count];
        unsafe.copyMemory(null, address, values, Unsafe.ARRAY_INT_BASE_OFFSET, (long) count << 2);
        return values;
    }

    public static void getInts(long address, int[] values, int count)
    {
        unsafe.copyMemory(null, address, values, Unsafe.ARRAY_INT_BASE_OFFSET, (long) count << 2);
    }

    public static void putInts(long address, int[] values)
    {
        unsafe.copyMemory(values, Unsafe.ARRAY_INT_BASE_OFFSET, null, address, (long) values.length << 2);
    }

    public static void putInts(long address, int[] values, int count)
    {
        unsafe.copyMemory(values, Unsafe.ARRAY_INT_BASE_OFFSET, null, address, (long) count << 2);
    }
}
